package ui;

import android.app.ProgressDialog;
import android.content.Context;
import android.hardware.bcreader.BCRBarCodeValue;
import android.hardware.bcreader.BCRListener;
import android.hardware.bcreader.BCRManager;
import android.hardware.bcreader.BCRTicketInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sxpjyy.monkey.mobilenurse.R;

import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import adapters.KFDListAdapter;
import adapters.SYDListAdapter;
import adapters.ZSDListAdapter;
import mytools.DoubleDatePickerDialog;
import mytools.MyBaseActivity;
import objects.InPatient;
import objects.Order_KFD_Child;
import objects.Order_KFD_Detail;
import objects.Order_KFD_Parent;
import objects.Order_SYD_Child;
import objects.Order_SYD_Detail;
import objects.Order_SYD_Parent;
import objects.Order_ZSD_Child;
import objects.Order_ZSD_Detail;
import objects.Order_ZSD_Parent;
import service.WebService;

public class DocOrdersActivity extends MyBaseActivity implements ViewPager.OnPageChangeListener, AdapterView.OnItemLongClickListener {
    private String TAG = "BCRSample";
    private BCRManager mBCRManager;
    private BCRTicketInfo mBCRTicketInfo[] = {null, null};

    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private OrdersPagerAdapter mOrderPagerAdapter;

    private String ZYH;

    private MyHandler handler;

    private String[] results = {null, null, null};
    private List<Order_SYD_Detail> mSYDList;
    private List<Order_ZSD_Detail> mZSDList;
    private List<Order_KFD_Detail> mKFDList;
    private Map<Order_SYD_Parent, List<Order_SYD_Child>> mSydDataSets;
    private Map<Order_ZSD_Parent, List<Order_ZSD_Child>> mZsdDataSets;
    private Map<Order_KFD_Parent, List<Order_KFD_Child>> mKfdDataSets;
    private String[] startDates = {null, null, null};
    private String[] endDates = {null, null, null};
    private BottomNavigationView[] bottomNavigationViews = {null, null, null};

    static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

    private String mScanResult;
    private String mFoundTMBH;
    private static ProgressDialog progressDialog = null;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_doc_orders);
        setNeedsMenuKey();
        onBindUI();
        handler = new MyHandler(this);
        BCRListener mListener = new MyListener();
        mBCRManager = BCRManager.getInstance();
        mBCRManager.registerListener(mListener);
        mOrderPagerAdapter = new OrdersPagerAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(mOrderPagerAdapter);
        mTabLayout.setupWithViewPager(mViewPager);
        mViewPager.addOnPageChangeListener(this);
    }

    private void onBindUI() {
        mTabLayout = findViewById(R.id.doc_order_tab);
        mViewPager = findViewById(R.id.doc_order_viewpager);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case 1300:
            case 1301:
                mBCRManager.open(this);
//                mBCRManager.startScan(BCRManager.SCAN_TYPE_SINGLE, BCRManager.SCAN_MODE_ONESHOT);
                break;
            case KeyEvent.KEYCODE_MENU:
                if (bottomNavigationViews[mViewPager.getCurrentItem()] != null) {
                    int VISIBILITY = bottomNavigationViews[mViewPager.getCurrentItem()].getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE;
                    bottomNavigationViews[mViewPager.getCurrentItem()].setVisibility(VISIBILITY);
                }
                break;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        InPatient inPatient = getMyApplication().getInPatient();
        if (inPatient != null) {
            ZYH = inPatient.getZYH();
            if (ZYH != null) {
                showProgressBar(this);
                Date date = new Date();
                String dateString = sdf.format(date);
                for (int i = 0; i < 3; i++) {
                    startDates[i] = dateString;
                    endDates[i] = dateString;
                }
                String[] parms = {ZYH, startDates[0], endDates[0]};
                new MyGetSYDTask().execute(parms);
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mBCRManager.stopScan();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mBCRManager.stopScan();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBCRManager.isReady()) {
            mBCRManager.close();
        }
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        switch (position) {
            case 0:
                showProgressBar(DocOrdersActivity.this);
                new MyGetSYDTask().execute(ZYH, startDates[0], endDates[0]);
                break;
            case 1:
                showProgressBar(DocOrdersActivity.this);
                new MyGetZSDTask().execute(ZYH, startDates[1], endDates[1]);
                break;
            case 2:
                showProgressBar(DocOrdersActivity.this);
                new MyGetKFDTask().execute(ZYH, startDates[2], endDates[2]);
                break;
            default:
                break;
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        int pageNum = mViewPager.getCurrentItem();
        switch (pageNum) {
            case 0:
                mFoundTMBH = mSYDList.get(position).getTMBH();
                break;
            case 1:
                mFoundTMBH = mZSDList.get(position).getTMBH();
                break;
            case 2:
                mFoundTMBH = mKFDList.get(position).getTMBH();
                break;
        }
        showChooseDialong(pageNum, mFoundTMBH);
        return false;
    }

    private class MyListener implements BCRListener {
        @Override
        public void onScanFinished(int scanType, String elapseTime) {
            Log.d(TAG, "onScanFinished");
            mBCRTicketInfo = mBCRManager.getTicketInfo();
            Message msg = new Message();
            if (mBCRTicketInfo != null) {
                msg.what = 0x11;
            } else {
                msg.what = 0x99;
            }
            handler.sendMessage(msg);
        }

        @Override
        public void onOpened(boolean isReady) {
            Log.d(TAG, "onOpened");
            if (isReady) {
                mBCRManager.enableCode(BCRBarCodeValue.CODE_TYPE_DATA_MATRIX);
                mBCRManager.enableCode(BCRBarCodeValue.CODE_TYPE_INTERLEAVED_2_OF_5);
                mBCRManager.enableCode(BCRBarCodeValue.CODE_TYPE_PDF417);
                mBCRManager.startScan(BCRManager.SCAN_TYPE_SINGLE, BCRManager.SCAN_MODE_CONTINUE);
            }
        }
    }

    private static class MyHandler extends Handler {

        WeakReference<DocOrdersActivity> mActivity;

        MyHandler(DocOrdersActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            DocOrdersActivity activity = mActivity.get();
            activity.cancelProgressBar();
            switch (msg.what) {
                case 0x99:
                    Toast.makeText(activity, "获取扫描结果失败！", Toast.LENGTH_SHORT).show();
                    activity.mBCRManager.stopScan();
                    break;
                case 0x11: //获取扫描结果成功
                    activity.mBCRManager.stopScan();
                    String result = activity.mBCRTicketInfo[0].getTicketValue();
                    if (result != null && !result.equals("") && !result.equals("failed")) {
                        activity.mScanResult = result;
                    } else {
                        break;
                    }
                    String type = activity.mScanResult.substring(0, 2);
                    switch (type) {
                        case "SY":
                            if (activity.mViewPager.getCurrentItem() != 0) {
                                activity.mViewPager.setCurrentItem(0);
                            } else {
                                activity.doFindDetail(0);
                            }
                            break;
                        case "ZS":
                            if (activity.mViewPager.getCurrentItem() != 1) {
                                activity.mViewPager.setCurrentItem(1);
                            } else {
                                activity.doFindDetail(1);
                            }
                            break;
                        case "KF":
                            if (activity.mViewPager.getCurrentItem() != 2) {
                                activity.mViewPager.setCurrentItem(2);
                            } else {
                                activity.doFindDetail(2);
                            }
                            break;
                        default:
                            break;
                    }
                    break;
                case 0x12:
                    if (activity.mScanResult != null) {
                        activity.doFindDetail(0);
                    }
                    break;
                case 0x13:
                    if (activity.mScanResult != null) {
                        activity.doFindDetail(1);
                    }
                    break;
                case 0x14:
                    if (activity.mScanResult != null) {
                        activity.doFindDetail(2);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    //显示等待对话框
    private void showProgressBar(Context context) {
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("正在获取信息。。。");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    //取消显示等待对话框
    private void cancelProgressBar() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.cancel();
            progressDialog = null;
        }
    }

    //根据条码号找医嘱
    private void doFindDetail(int which) {
        boolean isExisted = false;
        mFoundTMBH = null;
        if (mScanResult != null) {
            switch (which) {
                case 0: //输液单
                    for (Order_SYD_Detail sydDetail : mSYDList
                            ) {
                        final String TMBH = sydDetail.getTMBH();
                        if (TMBH != null && TMBH.equals(mScanResult)) {
                            mFoundTMBH = TMBH;
                            if (sydDetail.getHDBZ() != null && sydDetail.getHDBZ().equals("1")) {
                                Toast.makeText(DocOrdersActivity.this, "条码：" + TMBH + " 已核对过！", Toast.LENGTH_SHORT).show();
                            } else {
                                new AlertDialog.Builder(DocOrdersActivity.this).setTitle("提示！").setMessage("是否核对输液单：" + TMBH + "？").setPositiveButton("确定", (dialog, which1) -> {
                                    String[] parms = {getMyApplication().getUser().getYGDM(), TMBH};
                                    showProgressBar(DocOrdersActivity.this);
                                    new MyCheckExecuteOrderTask("checkSYD", 0).execute(parms);
                                }).setNegativeButton("取消", (dialog, which15) -> {
                                }).show();
                            }
                            isExisted = true;
                            break;
                        }
                    }
                    if (!isExisted) {
                        Toast.makeText(DocOrdersActivity.this, "该输液单不存在！", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 1://注射单
                    for (Order_ZSD_Detail zsdDetail : mZSDList
                            ) {
                        if (zsdDetail.getTMBH().equals(mScanResult)) {
                            final String TMBH = zsdDetail.getTMBH();
                            mFoundTMBH = TMBH;
                            if (zsdDetail.getHDBZ() != null && zsdDetail.getHDBZ().equals("1")) {
                                Toast.makeText(DocOrdersActivity.this, "条码：" + TMBH + " 已核对过！", Toast.LENGTH_SHORT).show();
                            } else {
                                new AlertDialog.Builder(DocOrdersActivity.this).setTitle("提示！").setMessage("是否核对注射单：" + TMBH + "？").setPositiveButton("确定", (dialog, which12) -> {
                                    String[] parms = {getMyApplication().getUser().getYGDM(), TMBH};
                                    showProgressBar(DocOrdersActivity.this);
                                    new MyCheckExecuteOrderTask("checkZSD", 0).execute(parms);
                                }).setNegativeButton("取消", (dialog, which13) -> {
                                }).show();
                            }
                            isExisted = true;
                            break;
                        }
                    }
                    if (!isExisted) {
                        Toast.makeText(DocOrdersActivity.this, "该注射单不存在！", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 2://口服单
                    for (Order_KFD_Detail kfdDetail : mKFDList
                            ) {
                        if (kfdDetail.getTMBH().equals(mScanResult)) {
                            final String TMBH = kfdDetail.getTMBH();
                            mFoundTMBH = TMBH;
                            if (kfdDetail.getHDBZ() != null && kfdDetail.getHDBZ().equals("1")) {
                                Toast.makeText(DocOrdersActivity.this, "条码：" + TMBH + " 已核对过！", Toast.LENGTH_SHORT).show();
                            } else {
                                new AlertDialog.Builder(DocOrdersActivity.this).setTitle("提示！").setMessage("是否核对口服单：" + TMBH + "？").setPositiveButton("确定", (dialog, which16) -> {
                                    String[] parms = {getMyApplication().getUser().getYGDM(), TMBH};
                                    showProgressBar(DocOrdersActivity.this);
                                    new MyCheckExecuteOrderTask("checkKFD", 0).execute(parms);
                                }).setNegativeButton("取消", (dialog, which14) -> {
                                }).show();
                            }
                            isExisted = true;
                            break;
                        }
                    }
                    if (!isExisted) {
                        Toast.makeText(DocOrdersActivity.this, "该口服单不存在！", Toast.LENGTH_SHORT).show();
                    }
                    break;
                default:
                    break;
            }
            mScanResult = null;
        }
    }

    private class OrdersPagerAdapter extends FragmentPagerAdapter {

        OrdersPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            if (position > 0) {
                OrdersPlaceholderFragment ordersPlaceholderFragment = (OrdersPlaceholderFragment) super.instantiateItem(container, position);
                ordersPlaceholderFragment.onAttach(DocOrdersActivity.this);
                return ordersPlaceholderFragment;
            }
            return super.instantiateItem(container, position);
        }

        @Override
        public Fragment getItem(int position) {
            return new OrdersPlaceholderFragment().newInstance(position + 1);
        }

        @Override
        public int getCount() {
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "输液类";
                case 1:
                    return "注射类";
                case 2:
                    return "口服类";
            }
            return null;
        }

        @Override
        public int getItemPosition(Object object) {
            return PagerAdapter.POSITION_NONE;
        }

    }

    public static class OrdersPlaceholderFragment extends Fragment {

        private final String ARG_SECTION_NUMBER = "section_number";

        private boolean[] isSelectAll = {false, false, false};
        DocOrdersActivity activity;

        public OrdersPlaceholderFragment() {
        }

        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            WeakReference<DocOrdersActivity> mActivity = new WeakReference<>((DocOrdersActivity) context);
            activity = mActivity.get();
        }

        public OrdersPlaceholderFragment newInstance(int sectionNumber) {
            OrdersPlaceholderFragment fragment = new OrdersPlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            int sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
            View rootView;
            switch (sectionNumber) {
                case 1: //输液单
                    rootView = inflater.inflate(R.layout.fragment_order_sy, container, false);
                    final ExpandableListView sy_listView = rootView.findViewById(R.id.check_order_sy_lv);
                    final LinearLayout sy_date_linear = rootView.findViewById(R.id.sy_top_linear);
                    final TextView sy_dateStart = rootView.findViewById(R.id.sy_date_start);
                    final TextView sy_dateEnd = rootView.findViewById(R.id.sy_date_end);
                    activity.bottomNavigationViews[0] = rootView.findViewById(R.id.sy_bottom_menu);
                    sy_dateStart.setText(activity.startDates[0]);
                    sy_dateEnd.setText(activity.endDates[0]);
                    final SYDListAdapter sydAdapter = new SYDListAdapter(activity);
                    sy_listView.setAdapter(sydAdapter);
                    if (activity.mSydDataSets != null && activity.mSydDataSets.size() > 0) {
                        sydAdapter.setDataSets(activity.mSydDataSets);
                        sydAdapter.notifyDataSetChanged();
                    }
                    int SY_VISIBILITY = sydAdapter.getChoicedCount() > 0 ? View.VISIBLE : View.GONE;
                    activity.bottomNavigationViews[0].setVisibility(SY_VISIBILITY);
                    activity.bottomNavigationViews[0].setOnNavigationItemSelectedListener(item -> {
                        String method = null;
                        int type = 0;
                        int zt = -1;
                        switch (item.getItemId()) {
                            case R.id.action_select_all:
                                if (activity.mSydDataSets != null && activity.mSydDataSets.size() > 0) {
                                    boolean isSelected = !isSelectAll[0];
                                    String text = isSelected ? "全不选" : "全选";
                                    for (int i = 0; i < activity.mSydDataSets.size(); i++) {
                                        sydAdapter.setChoicedItem(i, isSelected);
                                    }
                                    sydAdapter.notifyDataSetChanged();
                                    item.setTitle(text);
                                    isSelectAll[0] = isSelected;
                                }
                                break;
                            case R.id.action_check://复核医嘱
                                method = "checkSYD";
                                type = 0;
                                zt = 1;
                                break;
                            case R.id.action_execute: //执行医嘱
                                method = "executeSYD";
                                type = 1;
                                zt = 2; //状态为执行中
                                break;
                            case R.id.action_pause://暂停医嘱
                                method = "pauseresumeSYD";
                                type = 2;
                                zt = 4; //状态为暂停
                                break;
                            case R.id.action_resume://恢复医嘱
                                method = "pauseresumeSYD";
                                type = 4;
                                zt = 2; //状态为暂停
                                break;
                            case R.id.action_finish://完成医嘱
                                method = "executeSYD";
                                type = 3;
                                zt = 1; //状态为1
                                break;
                        }
                        if (method != null) {
                            if (sydAdapter.getChoicedCount() <= 0) {
                                Toast.makeText(activity, "没有选中项目！", Toast.LENGTH_SHORT).show();
                            } else {
                                StringBuilder tmbhs = new StringBuilder();
                                for (int i = 0; i < activity.mSydDataSets.size(); i++) {
                                    if (sydAdapter.getChoicedItem(i)) {
                                        Order_SYD_Parent parent = (Order_SYD_Parent) sydAdapter.getGroup(i);
                                        boolean condition = false;
                                        switch (type) {
                                            case 0:
                                                condition = parent.getHDBZ() == null || !parent.getHDBZ().equals("1");
                                                break;
                                            case 1:
                                                condition = parent.getHDBZ() != null && parent.getHDBZ().equals("1") && parent.getSYZT().equals("0");//未执行的输液单;
                                                break;
                                            case 2://暂停
                                                condition = parent.getHDBZ() != null && parent.getHDBZ().equals("1") && parent.getSYZT().equals("1");//执行中的输液单
                                                break;
                                            case 3://结束
                                                condition = parent.getHDBZ() != null && parent.getHDBZ().equals("1") && parent.getSYZT().equals("1");//执行中的输液单
                                                break;
                                            case 4://恢复暂停
                                                condition = parent.getHDBZ() != null && parent.getHDBZ().equals("1") && parent.getSYZT().equals("4");//暂停的输液单
                                                break;
                                        }
                                        if (condition) {
                                            if (tmbhs.toString().equals("")) {
                                                tmbhs.append(parent.getTMBH());
                                            } else {
                                                tmbhs.append(",").append(parent.getTMBH());
                                            }
                                        }
                                    }
                                }
                                if (!tmbhs.toString().equals("")) {
                                    String[] parms = {activity.getMyApplication().getUser().getYGDM(), tmbhs.toString(), "" + zt};
                                    activity.showProgressBar(activity);
                                    activity.new MyCheckExecuteOrderTask(method, type).execute(parms);
                                } else {
                                    Toast.makeText(activity, "没有符合条件的输液单！", Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                        return true;
                    });
                    sy_date_linear.setOnClickListener(v -> { //选择日期
                        Calendar calendarS = Calendar.getInstance();
                        Calendar calendarE = Calendar.getInstance();
                        String dateS = (String) sy_dateStart.getText();
                        String dateE = (String) sy_dateEnd.getText();
                        try {
                            Date date_S = sdf.parse(dateS);
                            Date date_E = sdf.parse(dateE);
                            calendarS.setTime(date_S);
                            calendarE.setTime(date_E);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        new DoubleDatePickerDialog(activity, 0, (startDatePicker, startYear, startMonthOfYear, startDayOfMonth, endDatePicker, endYear, endMonthOfYear, endDayOfMonth) -> {
                            String date_Start = startYear + "-" + (startMonthOfYear + 1) + "-" + startDayOfMonth;
                            String date_End = endYear + "-" + (endMonthOfYear + 1) + "-" + endDayOfMonth;
                            if (date_Start.compareTo(date_End) > 0) {
                                Toast.makeText(activity, "开始日期不能大于结束日期！", Toast.LENGTH_SHORT).show();
                            } else {
                                sy_dateStart.setText(date_Start);
                                sy_dateEnd.setText(date_End);
                                activity.startDates[0] = date_Start;
                                activity.endDates[0] = date_End;
                                activity.showProgressBar(activity);
                                activity.new MyGetSYDTask().execute(activity.ZYH, activity.startDates[0], activity.endDates[0]);
                            }
                        }, calendarS.get(Calendar.YEAR), calendarS.get(Calendar.MONTH), calendarS.get(Calendar.DATE), calendarE.get(Calendar.YEAR), calendarE.get(Calendar.MONTH), calendarE.get(Calendar.DATE),
                                false).show();
                    });
                    break;
                case 2: //注射单
                    rootView = inflater.inflate(R.layout.fragment_order_zs, container, false);
                    final ExpandableListView zs_listView = rootView.findViewById(R.id.check_order_zs_lv);
                    activity.bottomNavigationViews[1] = rootView.findViewById(R.id.zs_bottom_menu);
                    final LinearLayout zs_date_linear = rootView.findViewById(R.id.zs_top_linear);
                    final TextView zs_dateStart = rootView.findViewById(R.id.zs_date_start);
                    final TextView zs_dateEnd = rootView.findViewById(R.id.zs_date_end);
                    zs_dateStart.setText(activity.startDates[1]);
                    zs_dateEnd.setText(activity.endDates[1]);
                    final ZSDListAdapter zsdAdapter = new ZSDListAdapter(activity);
                    zs_listView.setAdapter(zsdAdapter);
                    if (activity.mZsdDataSets != null && activity.mZsdDataSets.size() > 0) {
                        zsdAdapter.setDataSets(activity.mZsdDataSets);
                        zsdAdapter.notifyDataSetChanged();
                    }
                    int ZS_VISIBILITY = zsdAdapter.getChoicedCount() > 0 ? View.VISIBLE : View.GONE;
                    activity.bottomNavigationViews[1].setVisibility(ZS_VISIBILITY);
                    zs_date_linear.setOnClickListener(v -> {
                        Calendar calendarS = Calendar.getInstance();
                        Calendar calendarE = Calendar.getInstance();
                        String dateS = (String) zs_dateStart.getText();
                        String dateE = (String) zs_dateEnd.getText();
                        try {
                            Date date_S = sdf.parse(dateS);
                            Date date_E = sdf.parse(dateE);
                            calendarS.setTime(date_S);
                            calendarE.setTime(date_E);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        new DoubleDatePickerDialog(activity, 0, (startDatePicker, startYear, startMonthOfYear, startDayOfMonth, endDatePicker, endYear, endMonthOfYear, endDayOfMonth) -> {
                            String date_Start = startYear + "-" + (startMonthOfYear + 1) + "-" + startDayOfMonth;
                            String date_End = endYear + "-" + (endMonthOfYear + 1) + "-" + endDayOfMonth;
                            if (date_Start.compareTo(date_End) > 0) {
                                Toast.makeText(activity, "开始日期不能大于结束日期！", Toast.LENGTH_SHORT).show();
                            } else {
                                zs_dateStart.setText(date_Start);
                                zs_dateEnd.setText(date_End);
                                activity.startDates[1] = date_Start;
                                activity.endDates[1] = date_End;
                                activity.showProgressBar(activity);
                                activity.new MyGetZSDTask().execute(activity.ZYH, activity.startDates[1], activity.endDates[1]);
                            }
                        }, calendarS.get(Calendar.YEAR), calendarS.get(Calendar.MONTH), calendarS.get(Calendar.DATE), calendarE.get(Calendar.YEAR), calendarE.get(Calendar.MONTH), calendarE.get(Calendar.DATE),
                                false).show();
                    });
                    activity.bottomNavigationViews[1].setOnNavigationItemSelectedListener(item -> {
                        String method = null;
                        int type = 0;
                        int zt = -1;
                        switch (item.getItemId()) {
                            case R.id.action_select_all:
                                if (activity.mZsdDataSets != null && activity.mZsdDataSets.size() > 0) {
                                    boolean isSelected = !isSelectAll[1];
                                    String text = isSelected ? "全不选" : "全选";
                                    for (int i = 0; i < activity.mZsdDataSets.size(); i++) {
                                        zsdAdapter.setChoicedItem(i, isSelected);
                                    }
                                    zsdAdapter.notifyDataSetChanged();
                                    item.setTitle(text);
                                    isSelectAll[1] = isSelected;
                                }
                                break;
                            case R.id.action_check: //医嘱复合
                                method = "checkZSD";
                                type = 0;
                                zt = 1;
                                break;
                            case R.id.action_execute:
                                method = "executeZSD";
                                type = 1;
                                zt = 2;
                                break;
                        }
                        if (method != null) {
                            if (!(zsdAdapter.getChoicedCount() > 0)) {
                                Toast.makeText(activity, "没有选中项目！", Toast.LENGTH_SHORT).show();
                            } else {
                                StringBuilder tmbhs = new StringBuilder();
                                for (int i = 0; i < activity.mZsdDataSets.size(); i++) {
                                    if (zsdAdapter.getChoicedItem(i)) {
                                        Order_ZSD_Parent parent = (Order_ZSD_Parent) zsdAdapter.getGroup(i);
                                        boolean condition = false;
                                        switch (type) {
                                            case 0:
                                                condition = parent.getHDBZ() == null || !parent.getHDBZ().equals("1");
                                                break;
                                            case 1:
                                                condition = parent.getHDBZ() != null && parent.getHDBZ().equals("1") && parent.getZSZT().equals("0");
                                                break;
                                        }
                                        if (condition) {
                                            if (tmbhs.toString().equals("")) {
                                                tmbhs.append(parent.getTMBH());
                                            } else {
                                                tmbhs.append(",").append(parent.getTMBH());
                                            }
                                        }
                                    }
                                }
                                String[] parms = {activity.getMyApplication().getUser().getYGDM(), tmbhs.toString(), "" + zt};
                                activity.showProgressBar(activity);
                                activity.new MyCheckExecuteOrderTask(method, type).execute(parms);
                            }
                        }
                        return true;
                    });
                    break;
                case 3://口服单
                    rootView = inflater.inflate(R.layout.fragment_order_kf, container, false);
                    final ExpandableListView kf_listView = rootView.findViewById(R.id.check_order_kf_lv);
                    final KFDListAdapter kfdAdapter = new KFDListAdapter(activity);
                    activity.bottomNavigationViews[2] = rootView.findViewById(R.id.kf_bottom_menu);
                    final LinearLayout kf_date_linear = rootView.findViewById(R.id.kf_top_linear);
                    final TextView kf_dateStart = rootView.findViewById(R.id.kf_date_start);
                    final TextView kf_dateEnd = rootView.findViewById(R.id.kf_date_end);
                    kf_dateStart.setText(activity.startDates[2]);
                    kf_dateEnd.setText(activity.endDates[2]);
                    kf_listView.setAdapter(kfdAdapter);
                    if (activity.mKfdDataSets != null && activity.mKfdDataSets.size() > 0) {
                        kfdAdapter.setDataSets(activity.mKfdDataSets);
                        kfdAdapter.notifyDataSetChanged();
                    }
                    int KF_VISIBILITY = kfdAdapter.getChoicedCount() > 0 ? View.VISIBLE : View.GONE;
                    activity.bottomNavigationViews[2].setVisibility(KF_VISIBILITY);
                    activity.bottomNavigationViews[2].setOnNavigationItemSelectedListener(item -> {
                        String method = null;
                        int type = 0;
                        int zt = -1;
                        switch (item.getItemId()) {
                            case R.id.action_select_all:
                                if (activity.mKfdDataSets != null && activity.mKfdDataSets.size() > 0) {
                                    boolean isSelected = !isSelectAll[2];
                                    String text = isSelected ? "全不选" : "全选";
                                    for (int i = 0; i < activity.mKfdDataSets.size(); i++) {
                                        kfdAdapter.setChoicedItem(i, isSelected);
                                    }
                                    kfdAdapter.notifyDataSetChanged();
                                    item.setTitle(text);
                                    isSelectAll[2] = isSelected;
                                }
                                break;
                            case R.id.action_check: //医嘱复合
                                method = "checkKFD";
                                type = 0;
                                zt = 1;
                                break;
                            case R.id.action_execute:
                                method = "executeZSD";
                                type = 1;
                                zt = 2;
                                break;
                        }
                        if (method != null) {
                            if (!(kfdAdapter.getChoicedCount() > 0)) {
                                Toast.makeText(activity, "没有选中项目！", Toast.LENGTH_SHORT).show();
                            } else {
                                StringBuilder tmbhs = new StringBuilder();
                                for (int i = 0; i < activity.mKfdDataSets.size(); i++) {
                                    if (kfdAdapter.getChoicedItem(i)) {
                                        Order_KFD_Parent parent = (Order_KFD_Parent) kfdAdapter.getGroup(i);
                                        boolean condition = false;
                                        switch (type) {
                                            case 0:
                                                condition = parent.getHDBZ() == null || !parent.getHDBZ().equals("1");
                                                break;
                                            case 1:
                                                condition = parent.getHDBZ() != null && parent.getHDBZ().equals("1") && parent.getKFZT().equals("0");
                                                break;
                                        }
                                        if (condition) {
                                            if (tmbhs.toString().equals("")) {
                                                tmbhs.append(parent.getTMBH());
                                            } else {
                                                tmbhs.append(",").append(parent.getTMBH());
                                            }
                                        }
                                    }
                                }
                                String[] parms = {activity.getMyApplication().getUser().getYGDM(), tmbhs.toString(), "" + zt};
                                activity.showProgressBar(activity);
                                activity.new MyCheckExecuteOrderTask(method, type).execute(parms);
                            }
                        }
                        return true;
                    });
                    kf_date_linear.setOnClickListener(v -> {
                        Calendar calendarS = Calendar.getInstance();
                        Calendar calendarE = Calendar.getInstance();
                        String dateS = (String) kf_dateStart.getText();
                        String dateE = (String) kf_dateEnd.getText();
                        try {
                            Date date_S = sdf.parse(dateS);
                            Date date_E = sdf.parse(dateE);
                            calendarS.setTime(date_S);
                            calendarE.setTime(date_E);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        new DoubleDatePickerDialog(activity, 0, (startDatePicker, startYear, startMonthOfYear, startDayOfMonth, endDatePicker, endYear, endMonthOfYear, endDayOfMonth) -> {
                            String date_Start = startYear + "-" + (startMonthOfYear + 1) + "-" + startDayOfMonth;
                            String date_End = endYear + "-" + (endMonthOfYear + 1) + "-" + endDayOfMonth;
                            if (date_Start.compareTo(date_End) > 0) {
                                Toast.makeText(activity, "开始日期不能大于结束日期！", Toast.LENGTH_SHORT).show();
                            } else {
                                kf_dateStart.setText(date_Start);
                                kf_dateEnd.setText(date_End);
                                activity.startDates[2] = date_Start;
                                activity.endDates[2] = date_End;
                                activity.showProgressBar(activity);
                                activity.new MyGetKFDTask().execute(activity.ZYH, activity.startDates[2], activity.endDates[2]);
                            }
                        }, calendarS.get(Calendar.YEAR), calendarS.get(Calendar.MONTH), calendarS.get(Calendar.DATE), calendarE.get(Calendar.YEAR), calendarE.get(Calendar.MONTH), calendarE.get(Calendar.DATE),
                                false).show();
                    });
                    break;
                default:
                    return null;
            }
            return rootView;
        }
    }

    /**
     * 核对、执行医嘱操作
     */
    private class MyCheckExecuteOrderTask extends AsyncTask<String, Integer, String> {

        private String METHOD;
        private int TYPE;//0:复核医嘱，1：执行医嘱,2:暂停输液单，3：结束输液单，4：回复暂停输液单
        private boolean taskSucceed = false;

        MyCheckExecuteOrderTask(String method, int type) {
            this.METHOD = method;
            this.TYPE = type;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            WebService checkWebService = new WebService(DocOrdersActivity.this);
            checkWebService.setMETHOD_NAME(METHOD);
            String result;
            checkWebService.setPARMS(params);
            result = checkWebService.getServerData();
            if (result == null || result.equals("null") || result.equals("0")) {
                taskSucceed = false;
                switch (TYPE) {
                    case 0://复核
                        return "医嘱复核失败！";
                    case 1://执行
                        return "医嘱执行失败！";
                    case 2://暂停
                        return "输液单暂停失败！";
                    case 3://结束
                        return "输液单完成失败！";
                    case 4://恢复
                        return "输液单暂停恢复失败！";
                    default:
                        return "执行操作失败";
                }
            } else {
                taskSucceed = true;
                switch (TYPE) {
                    case 0:
                        return "医嘱复核成功！";
                    case 1:
                        return "医嘱执行成功！";
                    case 2:
                        return "输液单暂停成功！";
                    case 3:
                        return "输液单完成成功！";
                    case 4://恢复
                        return "输液单暂停恢复成功！";
                    default:
                        return "执行操作成功";
                }
            }
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (taskSucceed) {
                switch (mViewPager.getCurrentItem()) {
                    case 0:
                        new MyGetSYDTask().execute(ZYH, startDates[0], endDates[0]);
                        break;
                    case 1:
                        new MyGetZSDTask().execute(ZYH, startDates[1], endDates[1]);
                        break;
                    case 2:
                        new MyGetKFDTask().execute(ZYH, startDates[2], endDates[2]);
                        break;
                }
            }
            cancelProgressBar();
            Toast.makeText(DocOrdersActivity.this, s, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 获取输液单操作
     */
    private class MyGetSYDTask extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            WebService getSYDWebService = new WebService(DocOrdersActivity.this);
            getSYDWebService.setMETHOD_NAME("getSYDInfo");
            String result;
            getSYDWebService.setPARMS(params);
            result = getSYDWebService.getServerData();
            if (result == null || result.equals("null") || result.equals("") || result.equals("[]")) {
                return "获取输液单列表为空！";
            } else {
                if (!result.equals(results[0])) {
                    results[0] = result;
                    Gson gson = new Gson();
                    mSYDList = gson.fromJson(results[0], new TypeToken<List<Order_SYD_Detail>>() {
                    }.getType());
                    if (mSYDList != null && mSYDList.size() > 0) {
                        return null;
                    } else {
                        return "获取输液单列表失败!";
                    }
                } else {
                    return "输液单数据未发生变化!";
                }
            }
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s != null) {
                cancelProgressBar();
                if (!s.equals("输液单数据未发生变化!")) {
                    Toast.makeText(DocOrdersActivity.this, s, Toast.LENGTH_SHORT).show();
                } else {
                    doFindDetail(0);
                }
            } else {
                doSetSYD(mSYDList);
            }
        }
    }

    /**
     * 获取注射单操作
     */
    private class MyGetZSDTask extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
//            isEcecuting[1] = true;
        }

        @Override
        protected String doInBackground(String... parms) {
            WebService getZSDWebService = new WebService(DocOrdersActivity.this);
            getZSDWebService.setMETHOD_NAME("getZSDInfo");
            String result;
            getZSDWebService.setPARMS(parms);
            result = getZSDWebService.getServerData();
            if (result == null || result.equals("null") || result.equals("") || result.equals("[]")) {
                return "获取注射单列表为空！";
            } else {
                if (!result.equals(results[1])) {
                    results[1] = result;
                    Gson gson = new Gson();
                    mZSDList = gson.fromJson(results[1], new TypeToken<List<Order_ZSD_Detail>>() {
                    }.getType());
                    if (mZSDList != null && mZSDList.size() > 0) {
                        return null;
                    } else {
                        return "获取注射单列表失败!";
                    }
                } else {
                    return "注射单数据未发生变化!";
                }
            }
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
//            isEcecuting[1] = false;
            if (s != null) {
                cancelProgressBar();
                if (!s.equals("注射单数据未发生变化!")) {
                    Toast.makeText(DocOrdersActivity.this, s, Toast.LENGTH_SHORT).show();
                } else {
                    doFindDetail(1);
                }
            } else {
                doSetZSD(mZSDList);
            }
        }
    }

    /**
     * 获取口服药操作
     */
    private class MyGetKFDTask extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
//            isEcecuting[2] = true;
        }

        @Override
        protected String doInBackground(String... parms) {
            WebService getKFDWebService = new WebService(DocOrdersActivity.this);
            getKFDWebService.setMETHOD_NAME("getKFDInfo");
            String result;
            getKFDWebService.setPARMS(parms);
            result = getKFDWebService.getServerData();
            if (result == null || result.equals("null") || result.equals("") || result.equals("[]")) {
                return "获取口服单列表为空！";
            } else {
                if (!result.equals(results[2])) {
                    results[2] = result;
                    Gson gson = new Gson();
                    mKFDList = gson.fromJson(results[2], new TypeToken<List<Order_KFD_Detail>>() {
                    }.getType());
                    if (mKFDList != null && mKFDList.size() > 0) {
                        return null;
                    } else {
                        return "获取口服单列表失败!";
                    }
                } else {
                    return "口服单数据未发生变化!";
                }
            }
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
//            isEcecuting[2] = false;
            if (s != null) {
                cancelProgressBar();
                if (!s.equals("口服单数据未发生变化!")) {
                    Toast.makeText(DocOrdersActivity.this, s, Toast.LENGTH_SHORT).show();
                } else {
                    doFindDetail(2);
                }
            } else {
                doSetKFD(mKFDList);
            }
        }
    }

    //设置输液单数据
    private void doSetSYD(List<Order_SYD_Detail> list) {
        List<Order_SYD_Parent> parentList = new ArrayList<>();
        mSydDataSets = new HashMap<>();
        for (Order_SYD_Detail orderSydDetail : list) {
            Order_SYD_Parent newParent = new Order_SYD_Parent(orderSydDetail.getSYDH(), orderSydDetail.getTMBH(), orderSydDetail.getYPYF(), orderSydDetail.getYFMC(), orderSydDetail.getSYSJ(), orderSydDetail.getSYPC(), orderSydDetail.getSYZT(), orderSydDetail.getHDBZ(), orderSydDetail.getHDRY(), orderSydDetail.getHDSJ(), orderSydDetail.getYHXM(), orderSydDetail.getKSSJ(), orderSydDetail.getKSGH(), orderSydDetail.getKSYG(), orderSydDetail.getJSSJ(), orderSydDetail.getJSGH(), orderSydDetail.getJSYG());
            Order_SYD_Child newChild = new Order_SYD_Child(orderSydDetail.getTMBH(), orderSydDetail.getYZXH(), orderSydDetail.getYZMC(), orderSydDetail.getYCJL(), orderSydDetail.getJLDW(), orderSydDetail.getYCSL(), orderSydDetail.getSLDW());
            boolean isExisted = false;
            int position = 0;
            for (Order_SYD_Parent parent : parentList) {
                if (parent.getSYDH().equals(newParent.getSYDH())) {
                    isExisted = true;
                    break;
                }
                position++;
            }
            if (!isExisted) {
                parentList.add(newParent);
                List<Order_SYD_Child> childList = new ArrayList<>();
                childList.add(newChild);
                mSydDataSets.put(newParent, childList);
            } else {
                mSydDataSets.get(parentList.get(position)).add(newChild);
            }
        }
        if (mSydDataSets.size() > 0) {
            mOrderPagerAdapter.notifyDataSetChanged();
            new Handler().post(() -> {
                Message msg = new Message();
                msg.what = 0x12;
                handler.sendMessage(msg);
            });
        }

    }

    //设置注射单数据
    private void doSetZSD(List<Order_ZSD_Detail> list) {
        List<Order_ZSD_Parent> parentList = new ArrayList<>();
        mZsdDataSets = new HashMap<>();
        for (Order_ZSD_Detail orderZsdDetail : list) {
            Order_ZSD_Parent newParent = new Order_ZSD_Parent(orderZsdDetail.getZSDH(), orderZsdDetail.getTMBH(), orderZsdDetail.getYPYF(), orderZsdDetail.getYFMC(), orderZsdDetail.getZSSJ(), orderZsdDetail.getSYPC(), orderZsdDetail.getZSZT(), orderZsdDetail.getHDSJ(), orderZsdDetail.getHDRY(), orderZsdDetail.getHDBZ(), orderZsdDetail.getYHXM());
            Order_ZSD_Child newChild = new Order_ZSD_Child(orderZsdDetail.getTMBH(), orderZsdDetail.getYZXH(), orderZsdDetail.getYZMC(), orderZsdDetail.getYCJL(), orderZsdDetail.getJLDW(), orderZsdDetail.getYCSL(), orderZsdDetail.getSLDW());
            boolean isExisted = false;
            int position = 0;
            for (Order_ZSD_Parent parent : parentList) {
                if (parent.getZSDH().equals(newParent.getZSDH())) {
                    isExisted = true;
                    break;
                }
                position++;
            }
            if (!isExisted) {
                parentList.add(newParent);
                List<Order_ZSD_Child> childList = new ArrayList<>();
                childList.add(newChild);
                mZsdDataSets.put(newParent, childList);
            } else {
                mZsdDataSets.get(parentList.get(position)).add(newChild);
            }
        }
        if (mZsdDataSets.size() > 0) {
            mOrderPagerAdapter.notifyDataSetChanged();
            new Handler().post(() -> {
                Message msg = new Message();
                msg.what = 0x13;
                handler.sendMessage(msg);
            });
        }
    }

    //设置口服单数据
    private void doSetKFD(List<Order_KFD_Detail> list) {
        List<Order_KFD_Parent> parentList = new ArrayList<>();
        mKfdDataSets = new HashMap<>();
        for (Order_KFD_Detail orderKfdDetail : list) {
            Order_KFD_Parent newParent = new Order_KFD_Parent(orderKfdDetail.getKFDH(), orderKfdDetail.getTMBH(), orderKfdDetail.getYPYF(), orderKfdDetail.getYFMC(), orderKfdDetail.getKFSJ(), orderKfdDetail.getKFZT(), orderKfdDetail.getHDBZ(), orderKfdDetail.getHDRY(), orderKfdDetail.getHDSJ(), orderKfdDetail.getYHXM());
            Order_KFD_Child newChild = new Order_KFD_Child(orderKfdDetail.getTMBH(), orderKfdDetail.getYZXH(), orderKfdDetail.getYZMC(), orderKfdDetail.getBZJL(), orderKfdDetail.getJLDW(), orderKfdDetail.getBZSL(), orderKfdDetail.getSLDW());
            boolean isExisted = false;
            int position = 0;
            for (Order_KFD_Parent parent : parentList) {
                if (parent.getKFDH().equals(newParent.getKFDH())) {
                    isExisted = true;
                    break;
                }
                position++;
            }
            if (!isExisted) {
                parentList.add(newParent);
                List<Order_KFD_Child> childList = new ArrayList<>();
                childList.add(newChild);
                mKfdDataSets.put(newParent, childList);
            } else {
                mKfdDataSets.get(parentList.get(position)).add(newChild);
            }
        }
        if (mKfdDataSets.size() > 0) {
            mOrderPagerAdapter.notifyDataSetChanged();
            new Handler().post(() -> {
                Message msg = new Message();
                msg.what = 0x14;
                handler.sendMessage(msg);
            });
        }
    }

    //显示虚拟菜单按钮
    private void setNeedsMenuKey() {
        try {
            Method setNeedsMenuKey = Window.class.getDeclaredMethod("setNeedsMenuKey", int.class);
            setNeedsMenuKey.setAccessible(true);
            int value = WindowManager.LayoutParams.class.getField("NEEDS_MENU_SET_TRUE").getInt(null);
            setNeedsMenuKey.invoke(getWindow(), value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showChooseDialong(int pageNum, String tmbh) {
        final String[] items = new String[]{"医嘱复核", "医嘱执行", "医嘱暂停", "暂停恢复", "医嘱完成"};
        AlertDialog.Builder mChooseDialogBuilder = new AlertDialog.Builder(DocOrdersActivity.this);
        mChooseDialogBuilder.setTitle("医嘱操作");
        mChooseDialogBuilder.setItems(items, (dialog, which) -> {
            Toast.makeText(DocOrdersActivity.this, items[which] + " click", Toast.LENGTH_SHORT).show();
//                switch (which) {
//                    case 0:
//                        Toast.makeText(DocOrdersActivity.this,items[which]+" click",Toast.LENGTH_SHORT).show();
//                        dialog.dismiss();
//                        break;
//                    case 1:
//                        showWarnDialog("是否要取消该医嘱计划？", "计划已取消");
//                        dialog.dismiss();
//                        break;
//                }
        }).show();
    }
}